<?php

namespace app\controller;

use app\BaseController;
use app\model\Order;
use app\model\ProductAttr;
use cgas\CGas;

class ChinaGas extends BaseController
{
    public function notifyData()
    {
        $attr = $this->app->make(ProductAttr::class);
        $attr_id = $attr->whereLike('code', 'cgas-%')->column("id");
        $model = $this->app->make(Order::class);
        $order = $model->where([
            ['state', '=', 1],
            ['attr_id', 'in', $attr_id],
            ['create_time', '<=', date("Y-m-d 00:00:00", strtotime("-60 day"))]
        ])->paginate(['list_rows' => 50, 'page' => $this->request->param("page", 1)])->toArray();
        $cgas = $this->app->make(CGas::class);
        $items = [];
        if (!empty($order['data'])) {
            foreach ($order['data'] as $value) {
                //查询券码是否已使用或者已过期
                $query = $cgas->query($value['code']);
                if (!empty($query) && $query['code'] == 0) {
                    $its = $query['data'];
                    switch ($its['status']) {
                        case 3:
                            $items[] = ['id' => $value['id'], 'state' => 2, 'used_time' => $query['data']['use_time']];
                            break;
                        case 4:
                        case 5:
                            $items[] = ['id' => $value['id'], 'state' => 3, 'cancel_time' => date("Y-m-d H:i:s")];
                            //回滚库存
                            $attr->where(['id' => $value['attr_id']])->inc("stock", 1)->save();
                            break;
                    }
                }
            }
        }
        if (!empty($items)) {
            $model->exists()->saveAll($items);
        }

//        return json($order);
        $page = $this->request->param("page", 1);
        if ($order['last_page'] > $page) {
            $page++;
            return redirect("?page=$page");
        }
    }

    public function autoStock()
    {
        //获取中石油的产品信息
        $product = $this->app->make(ProductAttr::class);
        $cgasStocks = $this->app->make(CGas::class)->lst();
        if (!empty($cgasStocks['data'])) {
            foreach ($cgasStocks['data'] as $value) {
                $product->where('code', '=', "cgas-$value[request_code]")->update([
                    'stock' => $value['total_num']
                ]);
            }
        }
        return json($cgasStocks);
    }
}
